#!/usr/bin/env bash

# Copyright (C) 2018-19 Akhil Narang
# SPDX-License-Identifier: GPL-3.0-only
# Kernel build script

# shellcheck disable=SC1090
# SC1090: Can't follow non-constant source. Use a directive to specify location.
source "${HOME}/scripts/functions"

if [[ -z ${KERNELDIR} ]]; then
    echo -e "Please set KERNELDIR"
    exit 1
fi

[[ -z ${DEVICE} ]] && { [[ "$(pwd)" =~ "raphael" ]] || [[ $* =~ "raphael" ]]; } && DEVICE=raphael
[[ -z ${DEVICE} ]] && { [[ "$(pwd)" =~ "phoenix" ]] || [[ $* =~ "phoenix" ]]; } && DEVICE=phoenix
[[ -z ${DEVICE} ]] && { [[ "$(pwd)" =~ "beryllium" ]] || [[ $* =~ "beryllium" ]]; } && DEVICE=beryllium
[[ -z ${DEVICE} ]] && DEVICE=beryllium

function tg() {
    case "${DEVICE}" in
        "beryllium")
            sendKernelBeryllium "${@:?}"
            ;;
        "raphael")
            sendTG "-1001317348741" "${@:?}"
            ;;
        "*")
            sendTG "92027269" "${@:?}"
            ;;
    esac
}

# These won't change
export SRCDIR="${KERNELDIR}/${DEVICE}"
export OUTDIR="${KERNELDIR}/${DEVICE}/obj"
export ANYKERNEL="${KERNELDIR}/anykernel/${DEVICE}"
export ARCH="arm64"
CCACHE="$(command -v ccache)"
if [[ ${USE_GCC} != "true" ]]; then
    [[ -z ${CLANG_DIR} ]] && export CLANG_DIR="/usr"
    export CLANG_TRIPLE="aarch64-linux-gnu-"
    export CC="${CLANG_DIR}/bin/clang"
    KBUILD_COMPILER_STRING=$(${CC} --version | head -n 1 | perl -pe 's/\(http.*?\)//gs' | sed -e 's/  */ /g' -e 's/[[:space:]]*$//')
fi
[[ -z ${GCC_DIR} ]] && export GCC_DIR="/usr"
CROSS_COMPILE="$(find ${GCC_DIR}/bin -name "aarch64-*-gcc" | tail -1 | sed 's/gcc$//')"
export CROSS_COMPILE_ARM32="${KERNELDIR}/arm-linux-androideabi-4.9/bin/arm-linux-androideabi-"
export DEFCONFIG="${DEVICE}_defconfig"
export ZIP_DIR="${KERNELDIR}/files/${DEVICE}"
export IMAGE="${OUTDIR}/arch/${ARCH}/boot/Image.gz-dtb"
export DOWNLOAD_BASE_URL="https://mirror.akhilnarang.dev/kernel/${DEVICE}/Test"
if [[ -z ${JOBS} ]]; then
    JOBS="$(grep -c '^processor' /proc/cpuinfo)"
fi
export DEVICE CCACHE KBUILD_COMPILER_STRING JOBS CROSS_COMPILE

function make_wrapper() {
    if [[ ${USE_GCC} == "true" ]]; then
        time make -j"${JOBS}" \
            O="${OUTDIR}" \
            ARCH="${ARCH}" \
            CROSS_COMPILE="${CCACHE} ${CROSS_COMPILE}" \
            CROSS_COMPILE_ARM32="${CCACHE} ${CROSS_COMPILE_ARM32}" \
            "${@}"
    else
        time make -j"${JOBS}" \
            O="${OUTDIR}" \
            ARCH="${ARCH}" \
            CC="${CCACHE} ${CC}" \
            CLANG_TRIPLE="${CLANG_TRIPLE}" \
            CROSS_COMPILE="${CROSS_COMPILE}" \
            CROSS_COMPILE_ARM32="${CROSS_COMPILE_ARM32}" \
            "${@}"
    fi
}

if [[ ! -d ${ANYKERNEL} ]]; then
    hub clone AnyKernel3 -b "${DEVICE}" "${ANYKERNEL}" || exit 1
fi

if [[ -z ${NAME} ]]; then
    export NAME="Illusion"
fi
NAME="${NAME}-${DEVICE}-$(date +%Y%m%d-%H%M)"
export NAME
export ZIPNAME="${NAME}.zip"
export FINAL_ZIP="${ZIP_DIR}/${ZIPNAME}"

[ ! -d "${ZIP_DIR}" ] && mkdir -pv "${ZIP_DIR}"
[ ! -d "${OUTDIR}" ] && mkdir -pv "${OUTDIR}"

cd "${SRCDIR}" || exit
rm -fv "${IMAGE}"

if [[ $* =~ "mrproper" ]]; then
    make_wrapper mrproper
fi

if [[ $* =~ "clean" ]]; then
    make_wrapper clean
fi

make_wrapper $DEFCONFIG || (echo "Failed to build with ${DEFCONFIG}, exiting!" &&
    exit 1)

START=$(date +"%s")
[[ $* =~ "upload" ]] && tg "Building!"
if [[ $* =~ "quiet" ]]; then
    make_wrapper |& ag -ia "error:|warning:"
else
    make_wrapper
fi
END=$(date +"%s")
DIFF=$((END - START))
echo -e "Build took $((DIFF / 60)) minute(s) and $((DIFF % 60)) seconds."
[[ $* =~ "upload" ]] && tg "Build took $((DIFF / 60)) minute(s) and $((DIFF % 60)) seconds."

if [[ ! -f ${IMAGE} ]]; then
    echo -e "Build failed :P"
    [[ $* =~ "upload" ]] && tg "Build failed!"
    exit 1
else
    echo -e "Build Succesful!"
fi

echo -e "Copying kernel image"
cp -v "${IMAGE}" "${ANYKERNEL}/"

cd - || exit
cd "${ANYKERNEL}" || exit
zip -r9 "${FINAL_ZIP}" ./* -x ".git/*" "README.md" ".gitignore" "*.zip"
md5sum "${FINAL_ZIP}" | sed -e "s|${ZIP_DIR}||" > "${FINAL_ZIP}.md5sum"
cd - || exit

if [ -f "$FINAL_ZIP" ]; then
    echo -e "$NAME zip can be found at $FINAL_ZIP"
    if [[ $* =~ "transfer" ]]; then
        echo -e "Uploading ${ZIPNAME} to https://transfer.sh/"
        transfer "${FINAL_ZIP}"
    fi
    if [[ $* =~ "upload" ]]; then
        echo -e "Uploading ${ZIPNAME}"
        case $(hostname) in
            "memebox")
                rsync -av --progress --delete "${ZIP_DIR}"/* ~/mirror/kernel/${DEVICE}/Test/
                ;;
            "TheLab")
                rsync -av --progress --delete "${ZIP_DIR}"/* /var/www/downloads.akhilnarang.me/kernel/${DEVICE}/Test/
                ;;
            *)
                rsync -av --progress --delete "${ZIP_DIR}"/* akhil@ssh.packet.resurrectionremix.com:mirror/kernel/${DEVICE}/Test/
                ;;
        esac
        mirrorsync
        tg "Download ${ZIPNAME/\.zip/} from [here](${DOWNLOAD_BASE_URL}/${ZIPNAME})"
    fi
else
    echo -e "Zip Creation Failed =("
fi # FINAL_ZIP check
